<?php
/**
 * Created by PhpStorm.
 * User: 侯佳
 * Date: 2018/1/31
 * Time: 12:25
 */
class pointAction extends Action
{
    /** 添加或修改积分方案
     * @param string $id id，修改时传
     * @param $name /名称
     * @param string $tagId 标签id
     * @param $status /状态0-未启用；1-启用
     * @param $default /是否默认，0-否/1-是
     * @param string $property 属性
     */
    public function operatePointScheme($id = '', $name, $tagId = '', $status = '', $default = '', $property = '')
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $schemeModel = M('module_point_scheme');
        $tagModel = M('module_point_tag');
        $schemeTagModel = M('module_point_scheme_tag');
        Session::switchCustomer($customerId);

        /*只能有一个默认，当要设置某个为默认时，先把其他默认的设为非默认*/
        if ($default == 1) {
            $data['default'] = 0;
            $setDefault = $schemeModel->where(['cid' => $customerId, 'default' => 1])->save($data);
            if (!is_numeric($setDefault)) {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '失败'
                ]);
                return;
            }
        }

        $arrTagId = explode(',', $tagId);
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'status' => $status,
            'createTime' => date('Y-m-d H:i:s', time()),
            'updateTime' => date('Y-m-d H:i:s', time()),
            'default' =>$default,
            'property' => $property
        );

        if (empty($id)) {
            $res = $schemeModel->add($data);
            foreach ($arrTagId as $value) {
                $tagData = [
                    'schemeId' => $res,
                    'tagId' => $value
                ];
                $schemeTagModel->add($tagData); //添加标签与方案对应记录
            }
            $schemeId = $res; //前端需要新添加的方案ID
        } else {
            unset($data['createTime']);
            $res = $schemeModel->where("id = $id")->save($data);
            $schemeTagModel->where("schemeId = $id")->delete();
            foreach ($arrTagId as $value) {
                $tagData = [
                    'schemeId' => $id,
                    'tagId' => $value
                ];
                $schemeTagModel->add($tagData);
            }
            $schemeId = $id;
        }

        if (is_numeric($res)) {
            $sql = $schemeModel->getLastSql();
            if ($id) {
                R('Log/add',array('pointScheme','','积分方案',op_update,$sql,'修改积分方案：' . $name));
            } else {
                R('Log/add',array('pointScheme','','积分方案',op_add,$sql,'添加积分方案：' . $name));
            }
            Output::instance()->object([
                'code' => 0,
                'schemeId' => $schemeId,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /** 删除积分方案
     * @param $id
     */
    public function deletePointScheme($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $schemeModel = M('module_point_scheme');
        Session::switchCustomer($customerId);

        $res = $schemeModel->where("id = $id")->setField('deleted', 1);

        if (is_numeric($res)) {
            $sql = $schemeModel->getLastSql();
            $name = $res = $schemeModel->where("id = $id")->getField('name');
            R('Log/add',array('pointScheme','','积分方案',op_delete,$sql,'删除积分方案：' . $name));
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**积分方案列表
     * @param string $keyword 搜索字段
     * @param string $startTime 时间搜索开始时间
     * @param string $endTime 时间搜索结束时间
     * @param string $status 状态筛选 0-未启用；1-启用
     * @param string $tagId 标签筛选id
     */
    public function pointSchemeList($keyword = '', $startTime = '', $endTime = '', $status = '', $tagId = '', $start, $limit)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $schemeModel = M('module_point_scheme');
        $tagModel = M('module_point_tag');
        $schemeTagModel = M('module_point_scheme_tag');
        Session::switchCustomer($customerId);

        /*根据传值组织查询条件*/
        if (!empty($tagId)) {
            $schemeIds = $schemeTagModel->where(['tagId' => $tagId])->getField('schemeId', true);
            $str_schemeIds = implode(',', $schemeIds);
            $where['id'] = ['in', $str_schemeIds];
        }
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['updateTime'] = ['BETWEEN', [$start_time, $end_time]];
        }
        if (!empty($keyword)) $where['name'] = ['LIKE', '%' . $keyword . '%'];
        if (is_numeric($status)) $where['status'] = ['eq', $status];
        $where['cid'] = $customerId;
        $where['deleted'] = 0;

        $list = $schemeModel->where($where)->order('updateTime desc')->limit($start, $limit)->select();
        /*插入标签信息*/
        foreach ($list as $key => $value) {
            $schemeTagWhere['schemeId'] = $value['id'];
            $tagIds = $schemeTagModel->where($schemeTagWhere)->getField('tagId', true);//获取标签id
            $tagConfigs = [];
            foreach ($tagIds as $tagId) {
                $tagName = $tagModel->where("id = $tagId")->getField('name');
                $tagConfig = ['id' => $tagId, 'tagName' => $tagName];
                array_push($tagConfigs, $tagConfig);
            }
            $list[$key]['tagConfigs'] = $tagConfigs;//插入标签信息
        }
        $total = $schemeModel->where($where)->count();
        (empty($list)) ? $list=[]:'';
        Output::instance()->object([
            'code' => 0,
            'data' => $list,
            'total' => $total
        ]);
    }

    /**获取积分方案详情
     * @param $schemeId /积分方案id
     */
    public function getPointSchemeById($schemeId)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $schemeModel = M('module_point_scheme');
        $tagModel = M('module_point_tag');
        $schemeTagModel = M('module_point_scheme_tag');
        Session::switchCustomer($customerId);

        $result = $schemeModel->where(['id' => $schemeId])->find();
        $schemeTagWhere['schemeId'] = $schemeId;
        $tagIds = $schemeTagModel->where($schemeTagWhere)->getField('tagId', true);
        $tagConfigs = [];
        /*插入标签信息*/
        foreach ($tagIds as $tagId) {
            $tagName = $tagModel->where("id = $tagId")->getField('name');
            $tagConfig = ['id' => $tagId, 'tagName' => $tagName];
            array_push($tagConfigs, $tagConfig);
        }
        $result['tagConfigs'] = $tagConfigs;

        Output::instance()->object([
            'code' => 0,
            'data' => $result
        ]);
    }

    /**添加标签
     * @param $name /标签名称
     */
    public function addPointTag($name)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('module_point_tag');
        Session::switchCustomer($customerId);

        $isHave = $tagModel->where(['name' => $name, 'deleted' => 0])->find();
        if ($isHave) {
            Output::instance()->object([
                'code' => 2,
                'msg' => '此名称的标签已经存在'
            ]);
            return;
        }
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'createTime' => date('Y-m-d H:i:s', time())
        );

        $res = $tagModel->add($data);

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'tagId' => $res,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**删除标签
     * @param $id
     */
    public function deletePointTag($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('module_point_tag');
        $schemeTagModel = M('module_point_scheme_tag');
        Session::switchCustomer($customerId);

        $tagModel->startTrans();
        $res = $tagModel->where("id = $id")->setField('deleted', 1);
        $res2 = $schemeTagModel->where("tagId = $id")->delete();//删除此标签与积分方案的关联关系

        if (is_numeric($res) && is_numeric($res2)) {
            $tagModel->commit();
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            $tagModel->rollback();
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**
     * 获取积分标签
     */
    public function getPointTag()
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('module_point_tag');
        Session::switchCustomer($customerId);

        $where['cid'] = $customerId;
        $where['deleted'] = 0;

        $tag = $tagModel->where($where)->select();
        (empty($tag)) ? $tag=[] : '';
        Output::instance()->object($tag);

    }

    /**用户积分列表
     * @param string $keyword 搜索条件
     * @param string $startTime
     * @param string $endTime
     */
    public function pointUserList($keyword = '', $startTime = '', $endTime = '', $start, $limit)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /* 2. 实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $userPointModel = M('module_user_point');
        Session::switchCustomer($customerId);

        /** 3. 组织查询条件 */
        $where['p.cid'] = $customerId;
        (!empty($keyword)) ? $where['u.fullName|u.phone'] = ['LIKE', '%' . $keyword . '%'] : '';
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['w.subscribe_time'] = ['BETWEEN', [$start_time, $end_time]];
        }
        $list = $userPointModel->alias('p')
            ->join('wx_'.$customerId.'_user u on u.id = p.userId')
            ->join('wx_'.$customerId.'_user_weixin_info w on w.userId = p.userId')
            ->where($where)
            ->field('p.*, u.fullName, u.phone, w.headimgurl, w.nickname, w.subscribe_time')
            ->limit($start, $limit)
            ->select();
        $total = $userPointModel->alias('p')
            ->join('wx_'.$customerId.'_user u on u.id = p.userId')
            ->join('wx_'.$customerId.'_user_weixin_info w on w.userId = p.userId')
            ->where($where)
            ->field('p.*, u.fullName, u.phone, w.headimgurl, w.nickname, w.subscribe_time')
            ->count();

        (empty($list)) ? $list = []:'';
        Output::instance()->object([
            'code' => 0,
            'total' => $total,
            'data' => $list
        ]);
    }

    /**用户积分明细列表
     * @param $userId /用户id
     * @param string $startTime
     * @param string $endTime
     * @param string $type 流水类型 0-收入、1-消费、2-扣除
     * @param $start
     * @param $limit
     */
    public function userPointBillList($userId, $startTime = '', $endTime = '', $type = '', $start, $limit)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /* 2. 实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $userPointModel = M('module_user_point');
        $pointBillModel = M('module_user_point_bill');
        Session::switchCustomer($customerId);

        /** 3. 组织查询条件 */
        $where['userId'] = $userId;
        $where['cid'] = $customerId;
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['createTime'] = ['BETWEEN', [$start_time, $end_time]];
        }
        (is_numeric($type)) ? $where['type'] = $type : '';

        $point = $userPointModel->where("userId = $userId and cid = $customerId")->getField('pointBalance');//获取积分余额
        $list = $pointBillModel->where($where)->order('createTime desc')->limit($start, $limit)->select();
        $total = $pointBillModel->where($where)->count();

        (empty($list)) ? $list = []:'';
        Output::instance()->object([
            'code' => 0,
            'point' => $point,
            'total' => $total,
            'data' => $list
        ]);
    }


    /**设置商品积分
     * @param $param /设置语句
     */
    public function setProductPoints($param)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /* 2. 实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModel = M('module_product');
        $model = M();
        Session::switchCustomer($customerId);

        $products = json_decode($param, true);
        foreach ($products as $product) {
            if ($product['points'] != null) {
                $where['id'] = $product['id'];
                $data['points'] = $product['points'];
                $res =$productModel->where($where)->save($data);
            } else {
                $res = $this->deletePointProduct($product['id'], 1);//如果没有设置积分，则此商品不属于积分兑换商品
            }

        }
        R('Log/add',array('pointScheme','','积分方案',op_update,'','设置商品积分'));
        Output::instance()->object([
            'code' => 0,
            'msg' => "ok"
        ]);
    }

    /**删除积分商品
     * @param $id
     */
    public function deletePointProduct($id, $needReturn = 0)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /* 2. 实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModel = M('module_product');
        Session::switchCustomer($customerId);

        $res = $productModel->where(['id' => $id])->setField('points', null);
        if (is_numeric($res)) {
            if ($needReturn == 1) {
                return true;
            } else {
                R('Log/add',array('pointScheme','','积分方案',op_delete,'','删除积分商品'));
                Output::instance()->object([
                    'code' => 0,
                    'msg' => 'ok'
                ]);
            }
        } else {
            if ($needReturn == 1) {
                return false;
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '失败'
                ]);
            }
        }
    }

    /**
     * 获取积分商城主题图
     */
    public function getPointPicture()
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /* 2. 实例化数据库*/
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $settingModel = M('customer_setting');
        Session::switchCustomer($cid);

        $pointPic = $settingModel->where("cid = $cid")->getField('pointPic');
        Output::instance()->object([
            'code' => 0,
            'data' => $pointPic
        ]);
    }

    /**设置积分商城主题图
     * @param $picUrl
     */
    public function setPointPicture($picUrl)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $settingModel = M('customer_setting');
        Session::switchCustomer($cid);

        $isHave = $settingModel->where("cid = $cid")->select();
        if (empty($isHave)) {
            $data['cid'] = $cid;
            $data['pointPic'] = $picUrl;
            $res = $settingModel->add($data);
        } else {
            $res = $settingModel->where("cid = $cid")->setField('pointPic', $picUrl);
        }

        if ($res) {
            $sql = $settingModel->getLastSql();
            R('Log/add',array('pointScheme', '', '积分方案', op_update, $sql, '设置积分商城主题图'));
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object(code_sql_error);
        }
    }

    /**根据id获取商品信息
     * @param $ids
     */
    public function getPointProById($ids)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModel = M('module_product');
        Session::switchCustomer($cid);

        $arr_ids = explode(',', $ids);
        $products = [];
        foreach ($arr_ids as $id) {
            $product = $productModel->where(['id' => $id])->field('id, name, points')->find();
            array_push($products, $product);
        }

        Output::instance()->object([
            'code' => 0,
            'data' => $products
        ]);
    }

//    /**
//     * 获取积分属性（积分属性改为字段存json，所以注释掉）
//     */
//    public function getPointProperty()
//    {
//        /** 1. 判断用户是否登录 */
//        $retVal = Session::init();
//        if (!$retVal) {
//            Output::instance()->resultCode(code_access_denied);
//            return;
//        }
//
//        $customerId = Session::$user['customerId'];
//        Session::switchCustomer(0);
//        $propertyModel = M('module_point_property');
//        Session::switchCustomer($customerId);
//
//        $where['cid'] = $customerId;
//        $list = $propertyModel->where($where)->select();
//        (empty($list)) ? $list=[]:'';
//        Output::instance()->object($list);
//    }
//
//    public function setPointProperty()
//    {
//        /** 1. 判断用户是否登录 */
//        $retVal = Session::init();
//        if (!$retVal) {
//            Output::instance()->resultCode(code_access_denied);
//            return;
//        }
//    }
    /**
     * 浏览商品或者文章增加积分
     * @param $pointSchemeId /积分方案id
     * @param $fromUserName   /转发人openid
     * @param $userId       /浏览人uid
     * @param $module       /模块
     * @param $moduleId     /模块id
     * @param $title        /文章名或者商品名
     * @return bool
     */
    public function addVisitPoint($pointSchemeId, $fromUserName, $userId, $module, $moduleId, $title,$cid)
    {
        //$cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $pointScheme_tab = M('module_point_scheme');
        $miShareFrom_tab = M('mishare_from');
        Session::switchCustomer($cid);
        $pointObj = D('Point', 'Logic');
        $user_tab = M('user');
        $pointSchemeInfo = $pointScheme_tab->where(['id' => $pointSchemeId,'status' => 1, 'deleted' => 0])->find();
        if(!$pointSchemeInfo){
            Log::write('积分方案不存在contentId:'.$moduleId.'|pointSchemeId:'.$pointSchemeId);
            return false;
        }else{
            $scheme = json_decode($pointSchemeInfo['property'], true);
            $ret = true;
            $sendUserId = $user_tab->where(['userName' => $fromUserName])->getField('id');
            foreach($scheme as $k=>$v){
                if($v['type'] == POINT_TYPE_SHARE_VISIT && ($v['status'] == 1)){
                    //同一篇文章被同一个人分享浏览多次,浏览人只增加一次积分
                    $shareVisitRet = $miShareFrom_tab->alias('a')
                        ->join('inner join wx_mishare_visit b on b.visitId = a.visitId')
                        ->field('a.id as shareId,b.id as visitId')
                        ->where(['a.uId' => $sendUserId, 'a.cid' => $cid, 'a.module' => $module,
                            'a.moduleId' => $moduleId, 'b.uId' => $userId, 'b.cid' => $cid, 'b.module' => $module,
                            'b.moduleId' => $moduleId])
                        ->find();
                    if(!$shareVisitRet){
                        //TODO 调用接口分别增加浏览人和分享人的积分
                        switch($module){
                            case 'micontent':
                                $visitChannel = '查看文章';
                                $sendChannel = '分享文章';
                                break;
                            case 'product':
                                $visitChannel = '查看商品';
                                $sendChannel = '分享商品';
                                break;
                            default :
                                $visitChannel = '查看文章';
                                $sendChannel = '分享文章';
                                break;
                        }
                        $visitPointRet = $pointObj->addPoint($userId, $v['visitPoint'], $module, $moduleId, $visitChannel, $title,
                            $pointSchemeId, $pointSchemeInfo['name']);
                        if(!$visitPointRet){
                            $ret = false;
                            Log::write('浏览人积分增加失败:moduleId:'.$moduleId.'|visitPoint:'.$v['visitPoint'].'|pointSchemeId:'.$pointSchemeId.
                                '|sendUserId:'.$sendUserId.'|userId:'.$userId.'|module:'.$module.'|visChan:'.
                                $visitChannel.'|title:'.$title.'|schemeName:'.$pointSchemeInfo['name']);
                        }
                        $sharePointRet = $pointObj->addPoint($sendUserId, $v['sendPoint'], $module, $moduleId, $sendChannel, $title,
                            $pointSchemeId, $pointSchemeInfo['name']);
                        if(!$sharePointRet){
                            $ret = false;
                            Log::write('分享人积分增加失败:moduleId:'.$moduleId.'|pointSchemeId:'.$pointSchemeId.
                                '|sendUserId:'.$sendUserId.'|userId:'.$userId.'|sendPoint:'.$v['sendPoint']);
                        }
                        break;
                    }
                    $ret = true;
                    break;
                }else if($v['type'] == POINT_TYPE_SHARE_VISIT){
                    $ret = false;
                    Log::write('积分方案未开启:moudleId:'.$moduleId.'|pointSchemeId'.$pointSchemeId);
                    break;
                }
            }
            return $ret;
        }
    }
}
